package com.zx.web.servelt;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author 章鑫
 * @version V1.0
 * @Project 2022-09-05
 * @Package com.zx.web.servelt
 * @Description:
 * @Date 2022/9/13 10:51
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//      String url = req.getRequestURI();
        String method = req.getParameter("method");

        Class<? extends BaseServlet> clazz = this.getClass();
//      System.out.println(clazz);
//        System.out.println("*****"+req.getClass());
        try {
            Method meth = clazz.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            try {
                Object result = meth.invoke(this, req, resp);
                if(result!=null){
                    String invoke = (String)result;
                    String[] arr = invoke.split(":");

                    if("redirect".equalsIgnoreCase(arr[0])){
                        resp.sendRedirect(arr[1]);
                    }else if("forward".equalsIgnoreCase(arr[0])){
                        req.getRequestDispatcher(arr[1]).forward(req,resp);
                    }
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
